package org.xm.sk.dao;

import java.util.Set;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.xm.sk.vo.ob.LocalShopList;
import org.xm.sk.vo.ob.ModelShop;
import org.xm.sk.vo.tb.Shop;

@Repository
public interface ShopRepository extends JpaRepository<Shop, Integer>,
        JpaSpecificationExecutor<Shop>, QuerydslPredicateExecutor<Shop> {

    Set<Shop> findByName(String name);

    @Modifying
    @Query("UPDATE FROM Shop u SET u.datalevel = 2, u.editer = :userid, u.editerName = :username WHERE u.id = :id")
    void delete(@Param("id") int id, @Param("userid") int userid,
            @Param("username") String username);

    @Modifying
    @Query("UPDATE FROM Shop u SET u.datalevel = 2, u.editer = :userid, u.editerName = :username WHERE u.id in :ids")
    void delete(@Param("ids") Set<Integer> ids, @Param("userid") int userid,
            @Param("username") String username);

    Page<ModelShop> listByLocal(Pageable arg0, Double longitude,
            Double latitude, Double range);

    //@Query("SELECT new org.xm.sk.vo.ob.ModelShop(u, sqrt((((:longitude - u.longitude) * PI() * 12656 * cos(((:latitude + u.latitude) / 2) * PI() / 180) / 180) * ((:longitude - u.longitude) * PI() * 12656 * cos(((:latitude + u.latitude) / 2) * PI() / 180) / 180)) + (((:latitude - u.latitude) * PI() * 12656 / 180) * ((:latitude - u.latitude) * PI() * 12656 / 180)))) FROM Shop u WHERE u.datalevel = 0 AND u.name like :name ORDER BY sqrt((((:longitude - u.longitude) * PI() * 12656 * cos(((:latitude + u.latitude) / 2) * PI() / 180) / 180) * ((:longitude - u.longitude) * PI() * 12656 * cos(((:latitude + u.latitude) / 2) * PI() / 180) / 180)) + (((:latitude - u.latitude) * PI() * 12656 / 180) * ((:latitude - u.latitude) * PI() * 12656 / 180))) ASC, u.id DESC")
    //@Query("SELECT new org.xm.sk.vo.ob.ModelShop(u, 216.254) FROM Shop u WHERE u.longitude = :longitude AND u.latitude = :latitude AND u.name like :name")
    Page<ModelShop> listByNameWithLocal(Pageable arg0, Double longitude,
            Double latitude, Double range, String keyStr);

    Page<LocalShopList> atList(Pageable pageable, Integer userid);

}
